package me.stephenj.contactsweb.controller;

import me.stephenj.contactsweb.service.LoginService;
import me.stephenj.contactsweb.utils.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;

@Controller
@CrossOrigin
@RequestMapping("/api")
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    LoginService loginService;

    @RequestMapping("getCurrentUser")
    @ResponseBody
    public CommonResult<String> getCurrentUser(HttpServletRequest request) {
        logger.info("getCurrentUser");
        String sessionId = loginService.getSessionId(request);
        String username = loginService.checkUser(sessionId);
        if (username != null) {
            return CommonResult.successReturn(username);
        }
        return CommonResult.errorReturn("尚未登录");
    }

    @RequestMapping("login")
    @ResponseBody
    public CommonResult<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
        logger.info("username={}", username);
        if (loginService.checkLogin(username, password)) {
            String sessionId = loginService.createNewSessionId(request, username);
            loginService.createNewCookie(response, sessionId);
            return CommonResult.successReturn(username);
        } else {
            return CommonResult.errorReturn("账号或密码不正确");
        }
    }

    @RequestMapping("logout")
    @ResponseBody
    public void logout(HttpServletResponse response, HttpServletRequest request) throws IOException {
        loginService.removeSessionId(request);
        loginService.cleanCookie(response);
        response.sendRedirect("/#/");
    }
}
